import {View, Text, TextInput, Alert} from 'react-native';
import React, {Component} from 'react';
import {Button} from '@rneui/themed';
import {MarqueeHorizontal} from "./MarqueeHorizontal";
import screen from "../../common/screen/Screen";
import lodash from 'lodash';

export default class BaseForm extends Component {
  constructor(props) {
    super(props);
    this.state = {
      formData: {},
      errors:[]
    };
    this.cleanFormData = this.cleanFormData.bind(this);
    this.getFormData = this.getFormData.bind(this);
    this.setFormData = this.setFormData.bind(this);
    this.setErrors = this.setErrors.bind(this);
  }

  cleanFormData() {
    this.setState({
      formData: {},
    });
  }

  getFormData() {
    return this.state.formData;
  }

  setFormData(formData) {
    this.setState({
      formData: formData,
    });
  }

  setErrors({message, content}) {
    if (content && content.length > 0) {
      let errors = content.map(item => {
        return {field: item.field, defaultMessage: item.defaultMessage}
      });
      this.setState({
        errors: errors
      })
    } else {
      Alert.alert(message, content);
    }
  }

  componentDidMount() {
    let formColumn = this.props.formColumn;
    formColumn.forEach(column => {
      if (column.defaultValue) {
        this.state.formData[column.field] = column.defaultValue;
      } else {
        this.state.formData[column.field] = '';
      }
      this.setState({
        formData: this.state.formData,
      });
    });
  }

  render() {
    let _this = this;
    const formColumn = this.props.formColumn;
    const operation = this.props.operation;
    if (operation.length > 2) {
      throw new Error('表单中只允许渲染2个按钮，请检查！');
    }

    function ErrMsgRender(props) {
      //必填校验
      if (props.column.required && !props.formData[props.column.field]) {
        return (
          <Text style={{color: 'red', fontSize: 12}}>
            {'请输入' + props.column.title}
          </Text>
        );
      }
      //大小校验
      if (
        props.column.rules &&
        (props.column.rules.min || props.column.rules.max) &&
        props.formData[props.column.field]
      ) {
        if (props.column.rules.min && props.column.rules.max) {
          if (
            props.column.type === 'TextInput' &&
            (props.column.rules.min >
              props.formData[props.column.field].length ||
              props.column.rules.max <
                props.formData[props.column.field].length)
          ) {
            return (
              <Text style={{color: 'red', fontSize: 12}}>
                {props.column.title +
                  '长度在' +
                  props.column.rules.min +
                  '-' +
                  props.column.rules.max +
                  '之间！'}
              </Text>
            );
          }
          if (
            props.column.type === 'NumberInput' &&
            (props.column.rules.min > props.formData[props.column.field] ||
              props.column.rules.max < props.formData[props.column.field])
          ) {
            return (
              <Text style={{color: 'red', fontSize: 12}}>
                {props.column.title +
                  '大小在' +
                  props.column.rules.min +
                  '-' +
                  props.column.rules.max +
                  '之间！'}
              </Text>
            );
          }
        } else if (props.column.rules.max) {
          if (
            props.column.type === 'TextInput' &&
            props.column.rules.max < props.formData[props.column.field].length
          ) {
            return (
              <Text style={{color: 'red', fontSize: 12}}>
                {props.column.title +
                  '长度需小于' +
                  props.column.rules.max +
                  '！'}
              </Text>
            );
          }
          if (
            props.column.type === 'NumberInput' &&
            props.column.rules.max < props.formData[props.column.field]
          ) {
            return (
              <Text style={{color: 'red', fontSize: 12}}>
                {props.column.title + '需小于' + props.column.rules.max + '！'}
              </Text>
            );
          }
        } else if (props.column.rules.min) {
          if (
            props.column.type === 'TextInput' &&
            props.column.rules.min > props.formData[props.column.field].length
          ) {
            return (
              <Text style={{color: 'red', fontSize: 12}}>
                {props.column.title +
                  '长度需大于' +
                  props.column.rules.min +
                  '！'}
              </Text>
            );
          }
          if (
            props.column.type === 'NumberInput' &&
            props.column.rules.min > props.formData[props.column.field]
          ) {
            return (
              <Text style={{color: 'red', fontSize: 12}}>
                {props.column.title + '需大于' + props.column.rules.min + '！'}
              </Text>
            );
          }
        }
      }
      //正则校验
      if (
        props.column.type === 'TextInput' &&
        props.column.rules &&
        props.column.rules.regex &&
        props.formData[props.column.field] &&
        !props.column.rules.regex.test(props.formData[props.column.field])
      ) {
        return (
          <Text style={{color: 'red', fontSize: 12}}>
            {props.column.rules.message}
          </Text>
        );
      }
      //返回报错信息
      if (
          _this.state.errors.find(item=>item.field === props.column.field)
      ) {
        return (
            <MarqueeHorizontal
                speed={60}
                width={screen.size.width*0.40}
                text={_this.state.errors.find(item=>item.field === props.column.field).defaultMessage}
                fontSize={12}
                fontColor={'red'}
            />
        );
      }
      return null;
    }

    const buttonLoading = button => {
      if (button.loading === null) {
        return false;
      } else if (typeof button.loading === 'function') {
        return button.loading();
      } else {
        return button.loading;
      }
    };

    const buttonDisabled = button => {
      if (button.disabled === null) {
        return false;
      } else if (typeof button.disabled === 'function') {
        return button.disabled();
      } else {
        return button.disabled;
      }
    };

    return (
      <View style={{flexDirection: 'column'}}>
        {formColumn.map((column, index) => {
          const borderColor = ErrMsgRender({column:column,formData: this.state.formData})?'red':null;
          return (
            <View
              key={index}
              style={{
                flexDirection: 'row',
                alignItems: 'center',
                marginLeft: '15%',
                marginTop: 10,
              }}>
              <View
                style={{
                  justifyContent: 'center',
                  width: '30%',
                }}>
                <View
                  style={{
                    flexDirection: 'row',
                    alignItems: 'center',
                    marginRight: '10%',
                  }}>
                  <View
                    style={{
                      justifyContent: 'center',
                      width: 7,
                    }}>
                    {column.required ? (
                      <Text
                        style={{fontSize: 12, color: 'red', marginBottom: 20}}>
                        {'*'}
                      </Text>
                    ) : null}
                  </View>
                  <Text
                    style={{fontSize: 16, color: '#262626', marginBottom: 15}}>
                    {column.title + ':'}
                  </Text>
                </View>
              </View>
              <View
                style={{
                  flex: 1,
                  marginRight: '20%',
                  justifyContent: 'flex-end',
                }}>
                <View
                  style={{
                    height: 40,
                    flexDirection: 'row',
                    alignItems: 'center',
                  }}>
                  <View style={{marginRight: 2}}>{column.prefix}</View>
                  <TextInput
                    style={{
                      width: '100%',
                      height: '100%',
                      borderWidth: 1,
                      flex: 1,
                      borderColor:borderColor
                    }}
                    editable={column.editable}
                    value={this.state.formData[column.field]}
                    onChangeText={text => {
                      this.state.formData[column.field] = text;
                      lodash.remove(this.state.errors, function(n) {
                        return n.field === column.field;
                      });
                      this.setState({
                        formData: this.state.formData,
                        errors:this.state.errors
                      });
                      if (column.onValueChange) {
                        column.onValueChange(text);
                      }
                    }}
                    secureTextEntry={column.security}
                    onSubmitEditing={() => {}}
                  />
                  <View style={{marginLeft: 2}}>{column.suffix}</View>
                </View>
                <View style={{height: 15}}>
                  <ErrMsgRender
                    column={column}
                    formData={this.state.formData}
                  />
                </View>
              </View>
            </View>
          );
        })}
        <View
          style={{
            flexDirection: 'row',
            justifyContent: 'center',
            width: '100%',
            marginTop: 20,
            paddingLeft: '10%',
            paddingRight: '10%',
          }}>
          {operation.map((button, index) => {
            return (
              <View
                key={index}
                style={{
                  height: 40,
                  marginLeft: '10%',
                  marginRight: '10%',
                  maxWidth: '30%',
                  flex: 1,
                }}>
                <Button
                  title={button.text}
                  onPress={async () => {
                    try {
                      _this.setState({
                        errors: []
                      })
                      await button.callback(this.getFormData());
                    } catch (e) {
                      console.log(e);
                      _this.setErrors(e);
                    }
                  }}
                  buttonStyle={[
                    {
                      backgroundColor: 'red',
                      borderRadius: 30,
                    },
                    button.style,
                  ]}
                  disabled={buttonDisabled(button)}
                  loading={buttonLoading(button)}
                />
              </View>
            );
          })}
        </View>
      </View>
    );
  }
}
